import {getCoursewareList, queryCoursewareLearn,getTrainingDetail} from "@/api/training-detail";
import {getCoursewareInfo, setCoursewareInfo,previewCoursewareInfo} from "@/api/courseware-study";
import {getPreviewCourseList} from "@/api/course-detail";
import {setLoginInfo,getLoginInfo,removeLoginInfo} from '@/utils/auth';
export default {
  name: "index",
  components: {},
  data() {
    return {
      iframeSrc: '',
      iframeWin: {},
      currentNav: 0,
      overflowY: 'scroll',//l
      classListWrapHeight: null,
      playPactionWrapHeight: null,
      current_timepoint: "",//接口返回的当前时间点 用于断点续学
      timepoint: "",//当前时间点
      current_auto_stop: "",//是否自动暂停
      studyStatus: "incomplete",//学习状态
      chapter: "1",//章节
      task: "0",//学习类型：0开始1继续
      courseWareList: [],//课件列表
      courseWareInfo: {},//课件信息
      courseId: this.$route.query.courseId,
      preview: this.$route.query.preview,
      trainingId: this.$route.query.trainingId,
      coursewareId: this.$route.query.coursewareId,
      courseWareIndex: this.$route.query.courseWareIndex,

      /*课件本章节播放完成的弹窗*/
      nextPalyDialog: false,//控制弹出
      nextPlayMsg: "",
      nextPlayFlag: false,
      sencond: 5,//设置初始倒计时
      timer: null,
      studyTime:null,

      isAllowDrag:false,//允许拖拽 0否 1是
      isPreventHangUp:false,//允许拖拽 0否 1是
    }
  },
  computed: {
    classListWrapStyle() {
      if (this.playPactionWrapHeight < this.classListWrapHeight) {
        this.overflowY = 'inherit';
        return {
          marginRight: '14px'
        }
      } else {
        this.overflowY = 'scroll';
        return {
          marginRight: '0'
        }
      }
    },
    heightl(){
      return document.body.clientHeight
    }
  },
  watch: {
    '$route'(to, from) {
      // 在mounted函数执行的方法，放到该处
      this.autoScroll();
      // this.iframeWin = this.$refs.iframeid.contentWindow;
      window.courseFrameFn = this.courseFrameFn;
      window.addEventListener('resize', () => {
        this.autoScroll();
      });
      this.courseId = this.$route.query.courseId,
      this.trainingId = this.$route.query.trainingId,
      this.coursewareId = this.$route.query.coursewareId,
      this.courseWareIndex = this.$route.query.courseWareIndex,
      this.getInfo();
      this.findECourseWare();
    }
  },
  methods: {
    autoScroll() {
      this.classListWrapHeight = this.$refs.classListWrap.clientHeight;
      this.playPactionWrapHeight = this.$refs.playPactionWrap.clientHeight;
    },
    //刷新按钮事件
    getInfo() {
      var data = {
        courseId: this.courseId,
        tcid: this.trainingId,
        coursewareId: this.coursewareId,
      };
      var getInfoDetail;
      if (this.preview === '0'){
        getInfoDetail = previewCoursewareInfo;
      } else {
        getInfoDetail = getCoursewareInfo;
      }
      getInfoDetail(data).then((response) => {
        this.courseWareInfo = response.data;
        // this.courseWareInfo.videoUrl = ' https://videoplay.ceivs.cn/ftpRoot/mp4/20210930154955A202109290301_3/contents/video_mp4/1.mp4'

        this.current_timepoint = response.data.timepoint;
        this.iframeSrc = 'static/resource/kj/an2_url/index.html';
        this.$nextTick(() => {
          console.log(this.$refs.iframeid.contentWindow)
          this.iframeWin = this.$refs.iframeid.contentWindow; // 确保在组件完全渲染后再访问
        });
      }).catch((err) => {
        this.$message.error(err.message || 'error')
      });
    },
    //刷新结束
    findECourseWare() {
      var data = {
        bindYear: "",
        courseId: this.courseId,
        tcId: this.trainingId
      };
      if (this.preview === '0'){
        getPreviewCourseList(this.courseId).then((response) =>{
          this.courseWareList = response.data;
          if (this.courseWareIndex > this.courseWareList.length - 1) {
            this.nextPlayFlag = false;
          } else {
            this.nextPlayFlag = true;
          }
        }).catch((err) =>{
          this.$message.error(err.message || 'error')

        });
      } else {
        getCoursewareList(data).then((response) => {
          this.courseWareList = response.data;
          if (this.courseWareIndex > this.courseWareList.length - 1) {
            this.nextPlayFlag = false;
          } else {
            this.nextPlayFlag = true;
          }
        }).catch((err) => {
          this.$message.error(err.message || 'error')
        });

      }





    },
    /*与课件交互的函数*/
    courseFrameFn() {
      var that = this;
      // 课件获取学习平台返回的对应值
      function LMSGetValue(name) {
        var value = "";
        if (name == "cmi.core.lesson_status") {
          if (value == "") {
            value = this.studyStatus;
          }
        } else if (name == "cmi.core.lesson_location") {
          value = that.current_timepoint;
        } else if (name == "cmi.core.auto_stop") {
          value = that.current_auto_stop;
        }else if (name == "cmi.core.videoUr1") {
          value = that.courseWareInfo.videoUrl;
        }
        return value;
      }

      // 保存课程学习信息
      function LMSSetValue(name, value) {
        console.log(name, value,that.nextPlayFlag)
        if (name == "cmi.core.lesson_location") {
          if (value.toString().indexOf(";") > 0) {
            var valueArray = value.split(';');///
            //value即为返回的时间点
            that.timepoint = valueArray[0];
            console.log(that.timepoint, "that.timepoint")
            var returntime = valueArray[1];
            var countTime = valueArray[2];
            that.setNewlyTime(returntime,countTime);
          } else {
            //value即为返回的时间点
            /* that.timepoint = value;
             sco = iframestr.substr(location + key.length, iframestr.length).replace(/\b(0+)/gi, "");
             //请求保存学习进度接口
             that.setTime(sco);*/
          }
        } else if (name == "cmi.core.lesson_status" && value == "completed") {
          // 课件播放完成
          if (that.nextPlayFlag) {
            that.nextPlay("即将播放下一集")
            //  播放下一集
          } else {
            //  播放最后一集
            that.nextPlay("课程播放已完成")
          }
        }
      }


      function ALTMESSAGE(messgae,title,fn) {
        that.$alert(messgae,title, {
          confirmButtonText: '确定',
          callback: action => {
            fn()
          }
        })
      }

      var isAllowDrag = this.isAllowDrag;
      var isPreventHangUp = this.isPreventHangUp;
      return {
        LMSGetValue: LMSGetValue,
        LMSSetValue: LMSSetValue,
        isAllowDrag: isAllowDrag,
        isPreventHangUp: isPreventHangUp,
        ALTMESSAGE:ALTMESSAGE,
      }
    },
    nextPlay(title) {
      this.nextPlayMsg = title;
      this.nextPalyDialog = true;
      this.getSencond();
    },
    getSencond() {
      const that = this;
      that.timer = window.setInterval(function () {
        --that.sencond;
        if (that.sencond === 0) {
          window.clearInterval(that.timer);
          // that.nextPalyDialog = false;
          var num = Number(that.courseWareIndex) + 1;
          if (that.nextPlayFlag) that.changeCouserware(that.courseWareList[num], num)//倒计时结束时运行的业务逻辑，这里是切换下一节
        }
      }, 1000)
    },
    sendMsg() {
      this.nextPalyDialog = false;
      window.clearInterval(this.timer);
      var num = Number(this.courseWareIndex) + 1;
      if (this.nextPlayFlag) {
        // this.updateProgress(this.courseWareList[num])
        this.changeCouserware(this.courseWareList[num], num);
      }
    },
    changeCouserware(courseware, courseWareIndex) {
      let routerJump = this.$router.resolve({
        path: '/studycourseware',
        query: {
          trainingId: this.trainingId,
          courseId: this.courseId,
          coursewareId: courseware.id,
          courseWareIndex
        }
      })
      this.iframeSrc ='';
      window.open(routerJump.href, '_self')
    },
    updateProgress(courseware){
      var data = {
        tcId: this.trainingId,
        courseId: this.courseId,
        coursewareId: courseware.id,
      }
      queryCoursewareLearn(data).then((response) =>{

      }).catch((err) =>{
        this.$message.error(err.message || 'error')
      });
    },
    setTime() {
      console.log("保存进度")

      var data = {
        bindYear: "",
        chapter: this.chapter,
        chapterTimepoint: "",
        courseId: this.courseId,
        coursewareId: this.coursewareId,
        studyLength: 0,
        studyTermType: "0",
        studystatus: this.studyStatus,
        task: this.task,
        tcid: this.trainingId,
        timepoint: "",
        userId: ""
      }
    },
    setNewlyTime(studyLength,countTime) {
      var point = ""
      if (Number(this.current_timepoint) && this.task == '0') {
        point = this.current_timepoint;
        console.log(point, "this.current_timepoint")
      } else {
        point = this.timepoint;
        console.log(point, "this.timepoint")
      }
      if (studyLength > 1 && this.preview !== '0') {
        var  studyTime = Number(getLoginInfo('studyTime'))
        if (studyTime == this.studyTime) {
          var data = {
            bindYear: "",
            chapter: this.chapter,
            chapterTimepoint: "",
            courseId: this.courseId,
            coursewareId: this.coursewareId,
            studyLength,
            countTime,
            studyTermType: "0",
            studystatus: this.studyStatus,
            task: this.task,
            tcid: this.trainingId,
            timepoint: point,
            userId: ""
          };
          setCoursewareInfo(data).then((response) => {
            this.task = '1';
            // this.getInfo();
          }).catch((err) => {
            if (err.code == -6){
              const video =this.iframeWin.document.querySelector('video');
              if (video) {
                video.pause();
              }
            } else {
              this.$confirm(err.message, '提示', {
                confirmButtonText: '确定',
                type: 'warning'
              });
            }
          });
        }else {
          const video =this.iframeWin.document.querySelector('video');
          if (video) {
            video.pause();
            this.$alert('检测到您有多个窗口在进行学习', '提示', {
              confirmButtonText: '刷新',
              showClose:false,
              closeOnClickModal:false,
              closeOnPressEscape:false,
              type: 'warning'
            }).then(() => {
              location.reload();
            })
          }
        }

      }else if (Number(studyLength) >= 300 && this.preview !== '0') {
        this.$confirm('预览已结束', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
      }
    },
    handleKeyDown(event) {
      // 检查按键是否是 F5
      if (event.code === 'F5' || (event.code === 'KeyR' && event.getModifierState('Control'))) {
        this.refreshPage();
      }
    },
    refreshPage(event) {
      // 显示确认框
      if (window.confirm('你查找的页面使用了你输入的信息。返回此页面可能导致重复你在那里进行的任何操作。是否继续?')) {
        // 用户点击确定，允许刷新或关闭
        event.returnValue = ''; // 对于IE和其他旧浏览器
      } else {
        // 用户点击取消，阻止刷新或关闭
        event.preventDefault(); // 阻止页面刷新或关闭
      }
    },
    getDetail() {
      getTrainingDetail(this.trainingId).then((response) => {
        this.isAllowDrag = response.data.isAllowDrag;
        this.isPreventHangUp = response.data.isPreventHangUp;
      }).catch((err) => {
        this.$message.error(err.message || 'error')
      });
    },
  },
  mounted() {
    this.autoScroll();
    // this.iframeWin = this.$refs.iframeid.contentWindow;
    window.addEventListener('resize', () => {
      this.autoScroll();
    });
    // 监听键盘事件
    window.addEventListener('keydown', this.handleKeyDown);
    // window.addEventListener('beforeunload', this.refreshPage);
    this.getDetail();
    this.getInfo();
    this.findECourseWare();
    window.courseFrameFn = this.courseFrameFn;
    this.studyTime = new Date().getTime();
    setLoginInfo('studyTime',this.studyTime);
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听
    window.removeEventListener('keydown', this.handleKeyDown);
    // window.removeEventListener('beforeunload', this.refreshPage);
  },
}

